#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Useage(const std::string proc)
{
    std::cout << "\n\rUseage: " << proc << " serverip serverport" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Useage(argv[0]);
        exit(1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 填充服务端套接字信息
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);                      // 主机转网络
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr)); // 字符串转网络序列

    while (true)
    {
        int cnt = 5;
        bool isreconnect = false;

        // 创建套接字
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cout << "create socket error" << std::endl;
            exit(-1);
        }

        do
        {
            // 客户端发起connect的时候，进行自动绑定，os随机选择
            int n = connect(sockfd, (const sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                isreconnect = true;
                cnt--;
                std::cout << "connect error...., reconnect: " << cnt << std::endl;
                sleep(2);
            }
            else
            {
                break;
            }

        } while (cnt && isreconnect);

        if (cnt == 0)
        {
            std::cout << "user ofline..." << std::endl;
        }

        while(true)
        {
            std::string message;
            std::cout << "please Enter# ";
            getline(std::cin, message);
            int n = write(sockfd, message.c_str(), sizeof(message));
            if (n < 0)
            {
                std::cout << "write err..." << std::endl;
                break;
            }
            char inbuffer[4096];
            n = read(sockfd, inbuffer, sizeof(inbuffer));
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << inbuffer << std::endl;
            }
            else
            {
                break;
            }
        }
        close(sockfd);
    }
    return 0;
}